//
//  IMAudioManagerAdapter.m
//  RNRecorder
//
//  Created by GJS on 2018/8/14.
//  Copyright © 2018年 Facebook. All rights reserved.
//

#import "AudioManagerAdapter.h"

#define kIdentifier @"AudioManagerIdentifier"

@implementation AudioManagerAdapter {
    NSMutableDictionary *audioManagers;
}

+ (instancetype)shareInstance{
    static AudioManagerAdapter *_audioManagerAdapter = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _audioManagerAdapter = [[self alloc] init];
    });
    
    return _audioManagerAdapter;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        //
        if (!audioManagers) {
            audioManagers = [NSMutableDictionary dictionary];
        }
    }
    
    return self;
}

- (void)dealloc {
    [audioManagers removeAllObjects];
    audioManagers = nil;
}

- (AudioManager *)audioManagerWithIdentifier:(NSString *)identifier {
    if (!identifier) {
        return self.defaultImAudioManager;
    }
    if (!audioManagers[identifier]) {
        AudioManager *audioManager = [[AudioManager alloc] init];
        [audioManagers setObject:audioManager forKey:identifier];
    }
    return audioManagers[identifier];
}

- (AudioManager *)audioManagerWithIdentifier:(NSString *)identifier withClass:(Class)aClass {
    if (!identifier) {
        return self.defaultImAudioManager;
    }
    aClass = [aClass isSubclassOfClass:[AudioManager class]] ? aClass : NSClassFromString(@"AudioManager");
    if (!audioManagers[identifier]) {
        AudioManager *audioManager = [[aClass alloc] init];
        [audioManagers setObject:audioManager forKey:identifier];
    }
    return audioManagers[identifier];
}

- (AudioManager *)defaultImAudioManager {
    if (!_defaultAudioManager) {
        _defaultAudioManager = [self audioManagerWithIdentifier:kIdentifier];
        _defaultAudioManager.audioTmpPath = [NSString stringWithFormat:@"%@/Library/appdata/chatbuffer", NSHomeDirectory()];
    }
    
    return _defaultAudioManager;
}

@end
